package com.example.mqttclient;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.ArrayList;
import java.util.List;

public class ThemeManager {
    private static ThemeManager instance;
    private static final String PREFS_NAME = "AppPrefs";
    private static final String KEY_THEME = "theme";
    private int currentTheme;
    private List<Activity> activities = new ArrayList<>();
    private Context context;

    private ThemeManager(Context context) {
        this.context = context.getApplicationContext();
        SharedPreferences prefs = this.context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        currentTheme = prefs.getInt(KEY_THEME, R.style.AppTheme_Light);
    }

    public static synchronized ThemeManager getInstance(Context context) {
        if (instance == null) {
            instance = new ThemeManager(context);
        }
        return instance;
    }

    public int getCurrentTheme() {
        return currentTheme;
    }

    public void setTheme(int theme) {
        currentTheme = theme;
        SharedPreferences.Editor editor = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit();
        editor.putInt(KEY_THEME, theme);
        editor.apply();

        // 动态更新视图
        for (Activity activity : activities) {
            updateActivityTheme(activity);
        }
    }

    public void registerActivity(Activity activity) {
        activities.add(activity);
        updateActivityTheme(activity);
    }

    public void unregisterActivity(Activity activity) {
        activities.remove(activity);
    }

    private void updateActivityTheme(Activity activity) {
        // 这里可以根据主题动态更新视图，例如更新背景颜色、文字颜色等
        if (currentTheme == R.style.AppTheme_Light) {
            // 设置亮色主题的视图样式
            activity.getWindow().getDecorView().setBackgroundColor(activity.getResources().getColor(android.R.color.white));
            // 可以继续添加其他视图更新逻辑
        } else {
            // 设置暗色主题的视图样式
            activity.getWindow().getDecorView().setBackgroundColor(activity.getResources().getColor(android.R.color.black));
            // 可以继续添加其他视图更新逻辑
        }
    }
}